package Worker;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * Near duplication of Master IO.java for security purpose
 */
public class IO {
    /** The upper bound of program size 2MB */
    public static int UPPERBOUNDSIZE = 2 * 1024 * 1024;

    /*
     * Flush data to given file on local worker
     */
    public static void writeFile(String filepath, byte[] file) 
    	throws IOException {
        File program = new File(filepath);

        FileOutputStream fileOutputStream = new FileOutputStream(program);
        fileOutputStream.write(file,0, file.length);

        fileOutputStream.close();
    }

    /*
     * Read data from given file on local worker
     */
    public static byte[] readFile(String filepath) throws IOException{
        byte[] buffer = new byte[IO.UPPERBOUNDSIZE];

        File programFile = new File(filepath);
        FileInputStream fileInputStream = new FileInputStream(programFile);
        int length = fileInputStream.read(buffer);
        fileInputStream.close();

        byte [] programBody = new byte[length];
        System.arraycopy(buffer,0, programBody,0,length);

        return programBody;
    }

    /*
     * Delete file on local worker
     */
    public static void deleteFile(String filepath) throws IOException {
        File programFile = new File(filepath);

        programFile.delete();

    }
}
